package com.gz.interceptor;

import com.alibaba.fastjson.JSON;
import com.gz.common.model.Customer;
import com.gz.utils.StringUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.redis.Redis;

/**
 * Created by frank on 2018/12/31.
 */
public class TokenInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation inv) {
        Ret ret = Ret.ok();
        ret.set("code", "301");
        ret.set("msg", "登录超时,Token过期");
        Controller controller = (Controller) inv.getController();
        String token = controller.getHeader("token");

        Customer customer = null;
        try {
            String customerJson = Redis.use("cms").get(token);
            if (StringUtil.isEmpty(customerJson)) {

            } else {
                customer = JSON.parseObject(customerJson, Customer.class);
            }

        } catch (Exception e) {

        }finally {
            if (customer == null) {
                controller.renderJson(ret);
            } else {
                controller.setAttr("customer", customer);
                controller.setAttr("token", token);
                inv.invoke();
            }
        }
    }

}
